package flc.ast.adapter;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.stark.cartoonavatarmaker.lib.core.AvatarColorBean;

import flc.ast.R;
import stark.common.basic.adaptermutil.StkProviderMultiAdapter;

/**
 * Author：daizhongbin on 2023/7/27
 * Email：1027154338@qq.com
 * Desc:
 */
public class FormatColorAdapter extends StkProviderMultiAdapter<AvatarColorBean> {

    private int selPos = -1;

    public FormatColorAdapter(int spanCount) {
        super(spanCount);
        addItemProvider(new ItemProvider());
    }

    public void setSelPos(int selPos) {
        if (this.selPos != selPos) {
            this.selPos = selPos;
            notifyDataSetChanged();
        }
    }

    private class ItemProvider extends BaseItemProvider<AvatarColorBean> {

        @Override
        public int getItemViewType() {
            return StkProviderMultiAdapter.TYPE_VIEW;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_cam_avatar_part;
        }

        @Override
        public void convert(@NonNull BaseViewHolder holder, AvatarColorBean colorBean) {
            int pos = holder.getAdapterPosition();
            holder.itemView.setSelected(selPos == pos);
            ImageView ivImg = holder.getView(R.id.ivImg);
            ImageView ivSelector = holder.getView(R.id.ivSelector);

            if (colorBean.imgId != 0) {
                ivImg.setImageResource(colorBean.imgId);
                ivImg.setBackgroundColor(Color.TRANSPARENT);
            } else {
                ivImg.setImageResource(0);
                Drawable drawable = ivImg.getBackground();
                if (drawable instanceof GradientDrawable) {
                    GradientDrawable gradientDrawable = (GradientDrawable) drawable;
                    gradientDrawable.setColor(colorBean.color);
                } else {
                    ivImg.setBackgroundColor(colorBean.color);
                }
            }
            if (selPos == pos) {
                ivSelector.setVisibility(View.VISIBLE);
            } else {
                ivSelector.setVisibility(View.GONE);
            }
        }
    }

}
